#!/bin/bash 
set -e


TMP=${TMP:-/tmp/work}
LOG=${LOG:-$HOME/logs/stage4}
SRC=${SRC:-/sources}

name=systemd
version=247

rm -rf $TMP
mkdir -p $TMP $LOG

tar xf $SRC/$name-$version.tar.xz -C $TMP

{ time \
   {

    cd $TMP/$name-$version
    
	patch -Np1 -i $SRC/$name-$version-upstream_fixes-1.patch

	sed -i 's/GROUP="render"/GROUP="video"/' rules.d/50-udev-default.rules.in

	mkdir build
	cd    build

	meson --prefix=/usr                 \
	      -Dblkid=true                  \
	      -Dbuildtype=release           \
	      -Ddefault-dnssec=no           \
	      -Dfirstboot=false             \
	      -Dinstall-tests=false         \
	      -Dldconfig=false              \
	      -Dman=auto                    \
	      -Drootprefix=                 \
	      -Drootlibdir=/lib             \
	      -Dsplit-usr=true              \
	      -Dsysusers=false              \
	      -Drpmmacrosdir=no             \
	      -Db_lto=false                 \
	      -Dhomed=true                  \
	      -Duserdb=true                 \
	      -Dmode=release                \
	      -Dpamconfdir=/etc/pam.d       \
	      -Ddocdir=/usr/share/doc/$name-$version \
	      ..

	ninja

	ninja install

	cat >> /etc/pam.d/system-session << "EOF"
# Begin Systemd addition
    
session  required    pam_loginuid.so
session  optional    pam_systemd.so

# End Systemd addition
EOF

	cat > /etc/pam.d/systemd-user << "EOF"
# Begin /etc/pam.d/systemd-user

account  required    pam_access.so
account  include     system-account

session  required    pam_env.so
session  required    pam_limits.so
session  required    pam_unix.so
session  required    pam_loginuid.so
session  optional    pam_keyinit.so force revoke
session  optional    pam_systemd.so

auth     required    pam_deny.so
password required    pam_deny.so

# End /etc/pam.d/systemd-user
EOF

    }
} 2>&1 | tee $name.log
    
[ $PIPESTATUS = 0 ] && mv $name.log $LOG || exit $PIPESTATUS

rm -fr $TMP
